//
//  WXNextWorking.m
//  qunfa
//
//  Created by Admin on 2017/8/18.
//  Copyright © 2017年 cuixiaocun. All rights reserved.
//

#import "WXNextWorking.h"
#import "XMLReader.h"
#import "AFNetworking.h"
#import "HomePage.h"
@implementation WXNextWorking
- (WXNextWorking*)init
{
    self= [super init];
    isreturn =@"NO";
    DEVICE= @"e767002199979185";
    numberImg =1;
    retString =@"0";
    isPhoneHidden =@"0";
//    _messageArr =[[NSMutableArray alloc]init];
    friendArr =[[NSMutableArray alloc]init];
    

   return self;
}
-(void)getErweima
{
    userDIC =[[NSMutableDictionary alloc]init];
    seqString =@"0";
    MemberList =[[NSMutableArray alloc]init];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型
    
    //你的接口地址
    NSString *url=[NSString stringWithFormat:@"https://login.wx.qq.com/jslogin"];
    NSDictionary *parameter = @{@"appid":@"wx782c26e4c19acffb",
                                @"fun":@"new",
                                @"lang":@"zh_CN",
                                @"_":timeString
                                
                                };
    [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject=%@",[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding]);
        
        NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSRange range = [str rangeOfString:@"\""]; //现获取要截取的字符串位置
        NSString * result = [str substringFromIndex:range.location]; //截取字符串
        NSLog(@"++++问问+%@",result);
        NSRange range2 = NSMakeRange (1,result.length-3);
        erweima = [result substringWithRange:range2];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [self.delegate returnTheERWEIMA:erweima];
        [self getER];
     
        NSLog(@"erweima请求成功JSON:%@", dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络连接失败");
    }];
    
    
}

- (void)getER{
    if ([isreturn isEqualToString:@"YES"]) {
        //如果是返回YES页面
        return;
        
    }else//如果没返回页面
    {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",nil];
        [manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型
        
        //你的接口地址
        NSString *url=[NSString stringWithFormat:@"https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login"];
        NSDictionary *parameter = @{@"loginicon":@"true",
                                    @"uuid":erweima,
                                    @"tip":@"1",
                                    @"_":timeString
                                    };
        
        [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress)
         {
             
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSString *str=[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
             if([str isEqualToString:@""]||[str isEqual:[NSNull null]])
             {
                 
             }else
             {
//                 NSLog(@"responseObject=%@",str);
                 NSRange range = [str rangeOfString:@"window.code="]; //现获取要截取的字符串位置
                 NSString * result = [str substringFromIndex:range.location]; //截取字符串
                 NSRange range2 = NSMakeRange (12,3); //现获取要截取的字符串位置
                 NSString * result2 = [result substringWithRange:range2]; //截取字符串
                 if([result2 intValue] ==200)//登录成功
                 {
                     NSRange range = [str rangeOfString:@"redirect_uri="""]; //现获取要截取的字符串位置
                     NSString * result = [str substringFromIndex:range.location]; //截取字符串
                     NSRange range2 = NSMakeRange (14,result.length-2-14);
                     NSString* url = [result substringWithRange:range2];
                     NSLog(@"\n======================================\n");
                     NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
                     NSLog(@"fields = %@",[fields description]);
                     NSLog(@"\n======================================\n");
                     //获取cookie方法1
                     NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
                     NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=ture&uuid=%@&tip=1&_=%@",erweima,timeString]]];
                     
                     for (NSHTTPCookie *cookie in cookies) {
                         [cookieDic setObject:cookie.value forKey:cookie.name];
                         NSLog(@"%@",cookie);
                     }
                     cookieValue = [NSMutableString stringWithFormat:@""];
                     
                     for (NSString *key in cookieDic) {
                         NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];

                         [cookieValue appendString:appendString];
                     }
                     NSLog(@"%@-----------------",cookieValue);
                     
                     
                     if([url rangeOfString:@"wx.qq.com"].location !=NSNotFound)//_roaldSearchText
                     {
                         _iswxqqOrIswxqq2 =@"";
                     }
                     else
                     {
                         _iswxqqOrIswxqq2 =@"2";
                         
                     }
                     _titleString  =[NSString stringWithFormat:@"%@&fun=new&version=v2",url];
                     [self send];
                     NSLog(@"%@",@"asdtyui");
                     
                 }else  if([result2 intValue] ==201)//扫描成功，显示头像
                 {
                     
                     if ([[NSString stringWithFormat:@"%@",str] rangeOfString:@"window.userAvatar"].location ==NSNotFound) {
                         [self performSelector:@selector(getER) withObject:nil afterDelay:2];
                         
                     }else
                     {
                         NSRange range = [str rangeOfString:@"window.userAvatar = '"]; //现获取要截取的字符串位置
                         NSString * result = [str substringFromIndex:range.location]; //截取字符串
                         NSRange range2 = NSMakeRange (41,result.length-43); //现获取要截取的字符串位置
                         NSString * result2 = [result substringWithRange:range2]; //截取字符串
                         NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:result2 options:NSDataBase64DecodingIgnoreUnknownCharacters];
                        _decodedImage = [UIImage imageWithData:decodedImageData];
//                         NSLog(@"1234567890-12345%@", result2);
                         if([isPhoneHidden isEqualToString:@"0"])
                         {
                             isPhoneHidden =@"1";
                             [self.delegate returnHeader:_decodedImage];

                         }

                         [self performSelector:@selector(getER) withObject:nil afterDelay:2];
                         
                     }
                     
                     
                 }else  if([result2 intValue] ==400)//二维码过期
                     
                 {
                     [ProgressHUD showError:@"二维码过期！"];
                     return ;
                 }else if([result2 intValue] ==408)//过期前25秒一循环
                     
                 {
                     [self getER];
                     
                 }
                 
             }
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             NSLog(@"网络连接失%@",error);
         }];
        
    }
    
    
    
    
    NSLog(@"123");
    
}

- (void)send
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",nil];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型
    
    //你的接口地址
    NSString *url=[NSString stringWithFormat:@"%@", _titleString];
    NSDictionary *parameter = @{};
    [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
         NSError *parseError = nil;
         if ([str isEqualToString:@""]) {
             
             return ;
         }
         NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
         // 打印 NSDictionary
         NSLog(@"%@", xmlDictionary);
         //如果授权失败@"此微信账号异常"
         if ([[NSString stringWithFormat:@"%@",[[[xmlDictionary  objectForKey:@"error"] objectForKey:@"ret"] objectForKey:@"text"]]isEqualToString:@"1203"]) {
             [ProgressHUD dismiss];
             [ProgressHUD showError:@"此微信账号异常"];

//             [MBProgressHUD showError:@"此微信账号异常" ToView:self.view];
             return ;
         }
         
         //如果成功
         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         skey =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"skey"] objectForKey:@"text"];
         sid =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"wxsid"] objectForKey:@"text"];
         uin =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"wxuin"] objectForKey:@"text"];
         pass_ticket =[[[xmlDictionary objectForKey:@"error"] objectForKey:@"pass_ticket"] objectForKey:@"text"];
         NSLog(@"\n======================================\n");
         NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
         NSLog(@"fields = %@",[fields description]);
         NSURL *url = [NSURL URLWithString:_titleString];
         NSLog(@"\n======================================\n");
         //获取cookie方法1
         NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
         NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:url];
         for (NSHTTPCookie *cookie in cookies) {
             [cookieDic setObject:cookie.value forKey:cookie.name];
             NSLog(@"%@",cookie);
         }
         cookieValue = [NSMutableString stringWithFormat:@""];
         for (NSString *key in cookieDic) {
             NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
             if([key isEqualToString:@"webwx_data_ticket"])
             {
                 webwx_data_ticket =[cookieDic valueForKey:key];
             }
             [cookieValue appendString:appendString];
         }
         NSLog(@"%@",cookieValue);
         [self allocTheInfo];//
         //webwxinit
         NSLog(@"erweima请求成功JSON:%@", dict);
     }
     
     
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"网络连接失败");
          }];
    
}

- (void)allocTheInfo//webwxinit
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"wx%@.qq.com",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Host"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com/?lang=zh_CN",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Referer"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com",_iswxqqOrIswxqq2] forHTTPHeaderField:@"Origin"];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"ture" forHTTPHeaderField:@"isAjaxRequest"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];//一般的服务器不推荐使用put和delete，所以这里就没有添加
    
    //创建你得请求url、设置请求头
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    
    NSString *urlString = [NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=%@&pass_ticket=%@",_iswxqqOrIswxqq2,timeString,pass_ticket];
    NSDictionary *parameter =[[NSDictionary alloc]init];
    NSDictionary *dic =@{
                         @"DeviceID":DEVICE,
                         @"Sid":sid,
                         @"Skey":skey,
                         @"Uin":uin,
                         };
    parameter = @{
                  @"BaseRequest":dic
                  };
    
    NSLog(@"%@",urlString);
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:@{} error:nil];
    
    NSString *param=[NSString stringWithFormat:@"%@", [parameter JSONFragment]];
    //把拼接后的字符串转换为data，设置请求体
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"bodyData=%@",param);
    
    //发起请求
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        
        if (!error) {
            friendArr =[[NSMutableArray alloc]init];
            
            [self webwxstatusnotify];//好友列表
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"dictdictdictdict%@",dict);
            selfName = [[dict objectForKey:@"User"] objectForKey:@"UserName"];
            NSLog(@"afor请求成功JSON:%@", [[dict objectForKey:@"User"] objectForKey:@"UserName"]);
            userDIC =[dict objectForKey:@"User"];
            [userDIC setObject:@"" forKey:@"jindu"];
            NSMutableArray *arr =[[NSMutableArray alloc]init];
            [arr addObjectsFromArray:[PublicMethod getObjectForKey:shopingCart]];
            [arr addObject:userDIC];
            [PublicMethod setObject:arr key:shopingCart];
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
}
//好友列表
- (void)webwxstatusnotify
{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型
    //你的接口地址
    NSString *url=[NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact",_iswxqqOrIswxqq2];
//    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    
    NSDictionary *parameter =@{
                               @"lang":@"zh_CN",
                               @"pass_ticket":pass_ticket,
                               @"r":timeString,
                               @"seq":seqString,
                               @"skey":skey
                               };
    
    NSLog(@"%@",url);
    NSLog(@"%@",parameter);
    [manager POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"请求成功JSON:%@", dict);
        NSLog(@"请求成功JSON:%@", [self logDic:dict]);
        NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        NSError *parseError = nil;
        
        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
        // 打印 NSDictionary
        NSLog(@"%@", xmlDictionary);
        seqString = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Seq"]];
        if ([seqString isEqualToString:@"0"]) {
            [MemberList addObjectsFromArray:[dict objectForKey:@"MemberList"]];
            
            for (int i=0; i<_pushArr.count; i++) {
                NSMutableArray *arr =[[NSMutableArray alloc]init];//符合条件的
                for (NSDictionary *dicMember in MemberList)
                {
                    NSLog(@"curr dicMember=%@",dicMember);
                if(![[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"VerifyFlag"] ]isEqualToString:@"0"]){
                        //公众号
                        
                    }
                    else
                    {
                        NSInteger numString =[[NSString stringWithFormat:@"%@",[_pushArr[i] objectForKey:@"num"]] integerValue];//friend人数
                        NSString *regionString =[NSString stringWithFormat:@"%@",[_pushArr[i] objectForKey:@"region"]];//地区
                        NSString *optionString =[NSString stringWithFormat:@"%@",[_pushArr[i] objectForKey:@"option"]];//1好友 2群组 3全部
                        NSString *sexString ;//性别 1男 2女 0全部
                        if ([[NSString stringWithFormat:@"%@",[_pushArr[i] objectForKey:@"sex"]]isEqualToString:@"1"]) {
                            sexString =@"1";
                            
                        }else if ([[NSString stringWithFormat:@"%@",[_pushArr[i] objectForKey:@"sex"]]isEqualToString:@"2"]) {
                            sexString =@"2";
                            
                        }else if ([[NSString stringWithFormat:@"%@",[_pushArr[i] objectForKey:@"sex"]]isEqualToString:@"0"]) {
                            sexString =@"0";
                            
                        }
                        {
                            
                        }
                        NSString *province;
                        NSString *city;
                        NSArray *temp=[regionString componentsSeparatedByString:@"/"];
                        if (([regionString isEqualToString:@""])||[regionString isEqualToString:@"全部"]||[regionString isEqual:[NSNull null]]||[regionString isEqualToString:@"<null>"]||[regionString isEqualToString:@"(null)"]) {
                            
                            province =@"";
                            city =@"";
                            
                        }else
                        {
                            {
                                if (temp.count==1) {
                                    city =@"";
                                    province =temp[0];
                                }else if (temp.count==2)
                                {
                                    province =temp[0];
                                    city =temp[1];
                                }else
                                {
                                    province =@"";
                                    city =@"";
                                }
                                
                            }
                        }
                        
                        
                        if ([optionString isEqualToString:@"2"]) {//群
                            if([[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"UserName"]] rangeOfString:@"@@"].location !=NSNotFound)
                            {
                                if (numString==0||numString >arr.count ) {
                                    [arr addObject:[dicMember objectForKey:@"UserName"]];
                                }
                                
                            }
                            
                        }else if([optionString isEqualToString:@"1"])//好友
                        {
                            
                            if([[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"UserName"]] rangeOfString:@"@@"].location !=NSNotFound)
                            {
                                continue;
                            }
//
                            if (((![[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"Sex"]]isEqualToString:[NSString stringWithFormat:@"%@",sexString]])&&(![sexString isEqualToString:@"0"]))) {
                                continue;
                            }
                            if (!(([province containsString:[dicMember objectForKey:@"Province"]]||[province isEqualToString:@""])&&([city containsString:[dicMember objectForKey:@"City"]]||[city isEqualToString:@""]))) {
                                continue;
                            }

                            if (numString==0||numString >arr.count ) {
                                [arr addObject:[dicMember objectForKey:@"UserName"]];
                            }
                            
                            
                        }else//所有
                        {
                            if([[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"UserName"]] rangeOfString:@"@@"].location !=NSNotFound)
                            {
                                if (numString==0||numString >arr.count ) {
                                    [arr addObject:[dicMember objectForKey:@"UserName"]];
                                }
                            }else
                            {
                                if((![[NSString stringWithFormat:@"%@",[dicMember objectForKey:@"Sex"]]isEqualToString:[NSString stringWithFormat:@"%@",sexString]])&&(![sexString isEqualToString:@"0"]))
                                {
                                    continue;
                                }
                                if (!(([province containsString:[dicMember objectForKey:@"Province"]]||[province isEqualToString:@""])&&([city containsString:[dicMember objectForKey:@"City"]]||[city isEqualToString:@""]))) {
                                    continue;
                                }
                                if (numString==0||numString >arr.count ) {
                                    [arr addObject:[dicMember objectForKey:@"UserName"]];
                                }
                                
                                
                            }
                            
                        }
                        
                    }
                    //测试李森的微信
                    if ([[dicMember objectForKey:@"PYQuanPin"]isEqualToString:@"xianglebantian"]) {
                        toName =[dicMember objectForKey:@"UserName"];
                        
                    }
                    
                }
                [friendArr addObject:arr];
                
            }
            NSLog(@"friendArr =%@",friendArr);
            
            currFirendArr =[[NSMutableArray alloc]init];
            currMessageArr =[[NSMutableArray alloc]init];
            [currMessageArr addObjectsFromArray: _messageArr[0]];
            [currFirendArr addObjectsFromArray: friendArr[0]];
            allNUMBER=0;
            dijiciIMG=0;
            [self numberImgUpload];
            
            NSLog(@"%@",friendArr);
            
            
            
            
        }else
        {
            
            [MemberList addObjectsFromArray:[dict objectForKey:@"MemberList"]];
            
            [self webwxstatusnotify];
            
            
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    
    
    
    
    
    
    
}
/***********************************分界线以下是循环部分******************************************/
- (void)numberImgUpload
{
    
    allNumberChange =0;
    for (int i=0;i<currMessageArr.count ; i++) {
        
        if([currMessageArr[i] objectForKey:@"img"])
        {
            [self upload:i];
        }else
        {
            allNumberChange++;
            if (allNumberChange==currMessageArr.count) {
                [self begainSende];
            }
            NSLog(@"12344567890-");
            
        }
    }
    
}
//上传图片到微信
- (void)upload:(int)num
{
    
    NSString *urlString = [NSString stringWithFormat:@"https://file.wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json",_iswxqqOrIswxqq2];
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    NSLog(@"messageArr[num]%@",[currMessageArr[num] objectForKey:@"img"]);
    UIImage *image = [[UIImage alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[currMessageArr[num] objectForKey:@"img"]]]]];
    NSData *data = UIImagePNGRepresentation(image);
    if (!image) {
        [ProgressHUD showError:@"请选择文字信息,暂不支持图片发送"];
        return;
    }
    NSInteger length = [data length];
    
    
    NSDictionary *paraData =[[NSDictionary alloc]init];
    NSDictionary *postData =[[NSDictionary alloc]init];
    NSDictionary *dic =@{
                         @"DeviceID":@"e165355858137910",
                         @"Sid":sid,
                         @"Skey":skey,
                         @"Uin":uin,
                         };
    paraData = @{
                 @"BaseRequest":dic,
                 @"UploadType":@2,
                 @"ClientMediaId":timeString,
                 @"TotalLen":[NSString stringWithFormat:@"%ld",length],
                 @"StartPos":@"0",
                 @"DataLen":[NSString stringWithFormat:@"%ld",length],
                 @"MediaType":@4,
                 //                     @"FromUserName":selfName,
                 //                     @"ToUserName":toName,
                 //                     @"FileMd5":[SendViewController getMD5WithData:data],
                 };
    
    postData =@{
                @"id":@"WU_FILE_0",
                @"name":@"ceshitupian.png",
                @"type":@"image/png",
                @"lastModifiedDate":[self getCurrentTime],
                @"size":[NSString stringWithFormat:@"%ld",(long)length],
                @"mediatype":@"pic",
                @"uploadmediarequest":[paraData JSONFragment],
                @"webwx_data_ticket":webwx_data_ticket,
                @"pass_ticket":pass_ticket,
                //                    @"filename":encodedImageStr,
                };
    //根据url初始化request
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",nil];
    NSString *url=urlString;
    
    [manager POST:url parameters:postData constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *eachImgData = data;
        //使用日期生成图片名称
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        [formData appendPartWithFileData :eachImgData name : @"filename" fileName : fileName mimeType : @"image/jpg/png/jpeg" ];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"图片请求成功JSON:%@", JSON);
        
        if ([[NSString stringWithFormat:@"%@",[[JSON objectForKey:@"BaseResponse"] objectForKey:@"Ret"]]isEqualToString:@"1"]) {
            NSLog(@"%@",@"参数不对");
            
        }else if ([[NSString stringWithFormat:@"%@",[[JSON objectForKey:@"BaseResponse"] objectForKey:@"Ret"]]isEqualToString:@"0"]) {
            NSLog(@"%@",@"参数");
            mediaId=[JSON objectForKey:@"MediaId"];
            dijiciIMG++;
            allNumberChange++;
            NSLog(@"%ld=%ld=%ld=++%ld++++%ld++++",allNumberChange,currMessageArr.count,numberImg,dijiciIMG,dijiciIMG);
            NSLog(@"%@,%d,%@",@{@"img":mediaId},num,currMessageArr);
            
            //            [currMessageArr[num] setObject:mediaId forKey:@"img"];
            
            [currMessageArr replaceObjectAtIndex:num withObject:@{@"img":mediaId}];
            if (numberImg==dijiciIMG&&allNumberChange==currMessageArr.count) {
                for (int i=0; i<currMessageArr.count; i++) {
                    [self begainSende];
                    
                }
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@", error.description);
    }];
    
}


//开始发送
- (void)begainSende
{
    //间隔时间
    [timer invalidate];
    timer = nil;
    timeNum =1;
    [ProgressHUD showSuccess:@"开始发送"];

//    [ProgressHUD show:@"正在发送中"];
    timer =  [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(function) userInfo:nil repeats:YES];
    NSLog(@"messageArr==%@",currMessageArr);
    
}
- (void)function
{
    NSMutableArray *arr =[[NSMutableArray alloc]init];
    [arr addObjectsFromArray:[PublicMethod getObjectForKey:shopingCart]];
    if (timeNum/currMessageArr.count>(unsigned long)currFirendArr.count) {
        
        [userDIC setObject:[NSString stringWithFormat:@"%lu/%ld",(unsigned long)currFirendArr.count,(unsigned long)currFirendArr.count] forKey:@"jindu"];
        NSLog(@"%@1234567890-=1234567890-=%@",selfName,[NSString stringWithFormat:@"%lu/%ld",(unsigned long)currFirendArr.count,(unsigned long)currFirendArr.count]);
        

    }else
    {
        [userDIC setObject:[NSString stringWithFormat:@"%lu/%ld",timeNum/currMessageArr.count,(unsigned long)currFirendArr.count] forKey:@"jindu"];
        NSLog(@"%@1234567890-=1234567890-=%@",selfName,[NSString stringWithFormat:@"%lu/%ld",timeNum/currMessageArr.count,(unsigned long)currFirendArr.count]);
    }
    for (int i=0; i<arr.count; i++) {
        if([[arr[i] objectForKey:@"UserName"]isEqualToString:selfName])
        {
            [arr replaceObjectAtIndex:i withObject:userDIC];
            [PublicMethod setObject:arr key:shopingCart];
            
            break;
        }
    }
    

    /*****循环*****/
    if (timeNum>currFirendArr.count*currMessageArr.count) {
        [timer invalidate];
        timer = nil;
        allNUMBER++;
        
        if (allNUMBER==_messageArr.count) {
            [ProgressHUD dismiss];
//            [MBProgressHUD showSuccess:[NSString stringWithFormat:@"发送完成,共发送给%ld人%ld条消息",currFirendArr.count,timeNum-1] ToView:self.view];
            return;
        }else if(allNUMBER<_messageArr.count)
        {
            currFirendArr =[[NSMutableArray alloc]init];
            currMessageArr =[[NSMutableArray alloc]init];
            [currMessageArr addObjectsFromArray: _messageArr[allNUMBER]];
            [currFirendArr addObjectsFromArray: friendArr[allNUMBER]];
            [self numberImgUpload];
        }
        return;
        
        
    }else
    {
        [self sendMessageOrImg:(int)((timeNum-1)/currMessageArr.count) sendTiao:(int)((timeNum-1)%currMessageArr.count)];//发消息
        timeNum++;//时间相加
        
    }
    
   
}
- (void)sendMessageOrImg:(int)ren sendTiao:(int)tiao
{
    NSDictionary *dic =currMessageArr[tiao];
    if ([dic objectForKey:@"img"]) {
        [self sendMessageImg:ren sendTiao:tiao];
    }else
    {
        [self sendMessage:ren sendTiao:tiao];
    }
    
}
//发消息
- (void)sendMessage:(int)ren sendTiao:(int)tiao
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"wx%@.qq.com",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Host"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com/?lang=zh_CN",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Referer"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com",_iswxqqOrIswxqq2] forHTTPHeaderField:@"Origin"];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"ture" forHTTPHeaderField:@"isAjaxRequest"];
//    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];//一般的服务器不推荐使用put和delete，所以这里就没有添加
    //创建你得请求url、设置请求头
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    NSString *urlString = [NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?lang=zh_CN&pass_ticket=%@",_iswxqqOrIswxqq2,pass_ticket];
    NSDictionary *baseRequest =@{
                                 @"DeviceID":DEVICE,
                                 @"Sid":sid,
                                 @"Skey":skey,
                                 @"Uin":uin,
                                 };
    
    NSDate* dat2 = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a2=[dat2 timeIntervalSince1970]*1000;
    NSLog(@"a2==%f",a2);
    NSString* timeString3 = [NSString stringWithFormat:@"%f", a2 ];//转为字符型
    NSRange range = [timeString3 rangeOfString:@"."]; //现获取要截取的字符串位置
    NSString * result = [timeString3 substringToIndex:range.location]; //截取字符串
    int num = (arc4random() % 10000);
    NSString *clientMsgId =[NSString stringWithFormat:@"%@%.4d",result,num];
//    UITextView *texV =[self.view viewWithTag:100];
    
    NSDictionary *msg =@{
                         @"ClientMsgId":clientMsgId,
                         @"Content":[currMessageArr[tiao] objectForKey:@"content"],
                         @"FromUserName":selfName,
                         @"LocalID":clientMsgId,
                         @"ToUserName":currFirendArr[ren],
                         @"Type":@"3",
                         };
    NSDictionary *parameter =@{
                               @"BaseRequest":baseRequest,
                               @"Msg":msg,
                               @"Scene":@"0"
                               };
    NSLog(@"%@",urlString);
    NSLog(@"%@",parameter);
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:@{} error:nil];
    NSString *param=[NSString stringWithFormat:@"%@", [parameter JSONFragment]];
    //把拼接后的字符串转换为data，设置请求体
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"bodyData=%@",param);
    
    //发起请求
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            NSLog(@"step1.responseObject=%@",[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding]);
            NSError *parseError = nil;
            NSLog(@"[manager.requestSerializer HTTPRequestHeaders]=%@",[manager.requestSerializer HTTPRequestHeaders]);
//            NSLog(@"[parameter==]%@",[HomePage dictionaryToJson:parameter ]);
            
            NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            NSLog(@"allinfors%@",str);
            NSLog(@"allinforP%@",parameter);
            
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
            // 打印 NSDictionary
            NSLog(@"%@", xmlDictionary);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"afor请求成功JSON:%@", dict);
            if ([[NSString stringWithFormat:@"%@",[[dict objectForKey:@"BaseResponse"] objectForKey:@"Ret"]]isEqualToString:@"1101"]) {
                
                [timer invalidate];
                timer = nil;

            }
            
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
    
}

//发消息图片
- (void)sendMessageImg:(int)ren sendTiao:(int)tiao
{
    if ([retString isEqualToString:@"0"]) {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json", @"text/html", @"text/plain",@"text/javascript",@"application/json",nil];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"wx%@.qq.com",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Host"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com/?lang=zh_CN",_iswxqqOrIswxqq2]forHTTPHeaderField:@"Referer"];
    [ manager.requestSerializer setValue:[NSString stringWithFormat:@"https://wx%@.qq.com",_iswxqqOrIswxqq2] forHTTPHeaderField:@"Origin"];
    [ manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 6.1)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"ture" forHTTPHeaderField:@"isAjaxRequest"];
//    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD"]];//一般的服务器不推荐使用put和delete，所以这里就没有添加
    
    //创建你得请求url、设置请求头
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [[NSString stringWithFormat:@"%f", a] substringToIndex:13];//转为字符型
    NSString *urlString = [NSString stringWithFormat:@"https://wx%@.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket=%@",_iswxqqOrIswxqq2,pass_ticket];
    NSDictionary *baseRequest =@{
                                 @"DeviceID":DEVICE,
                                 @"Sid":sid,
                                 @"Skey":skey,
                                 @"Uin":uin,
                                 };
    
    NSDate* dat2 = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a2=[dat2 timeIntervalSince1970]*1000;
    NSLog(@"a2==%f",a2);
    NSString* timeString3 = [NSString stringWithFormat:@"%f", a2 ];//转为字符型
    NSRange range = [timeString3 rangeOfString:@"."]; //现获取要截取的字符串位置
    NSString * result = [timeString3 substringToIndex:range.location]; //截取字符串
    int num = (arc4random() % 10000);
    NSString *clientMsgId =[NSString stringWithFormat:@"%@%.4d",result,num];
    
    NSDictionary *msg =@{
                         @"ClientMsgId":clientMsgId,
                         @"MediaId":[currMessageArr[tiao] objectForKey:@"img"],
                         @"FromUserName":selfName,
                         @"LocalID":clientMsgId,
                         @"ToUserName":currFirendArr[ren],
                         //                         @"ToUserName":toName,
                         @"Type":@"3",
                         };
    NSDictionary *parameter =@{
                               @"BaseRequest":baseRequest,
                               @"Msg":msg,
                               @"Scene":@"0"
                               };
    NSLog(@"%@",urlString);
    NSLog(@"%@",parameter);
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:@{} error:nil];
    NSString *param=[NSString stringWithFormat:@"%@", [parameter JSONFragment]];
    //把拼接后的字符串转换为data，设置请求体
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"bodyData=%@",param);
    //发起请求
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            NSLog(@"step1.responseObject=%@",[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding]);
            NSError *parseError = nil;
            NSLog(@"[manager.requestSerializer HTTPRequestHeaders]=%@",[manager.requestSerializer HTTPRequestHeaders]);
//            NSLog(@"[parameter==]%@",[HomePage dictionaryToJson:parameter ]);
            
            NSString *str =[[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            NSLog(@"allinfors%@",str);
                       NSLog(@"allinforP%@",parameter);
            
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
            // 打印 NSDictionary
            NSLog(@"%@", xmlDictionary);
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSLog(@"afor请求成功JSON:%@", dict);
            
            if ([[NSString stringWithFormat:@"%@",[[dict objectForKey:@"BaseResponse"]objectForKey:@"Ret" ]]  isEqualToString:@"0"]) {
                
                retString =@"0";//0代表成功
            }else
            {
                retString =@"1";//1代表异常
            }

        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    }
    
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}


- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =[[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                                     withString:@"\\U"];
    NSString *tempStr2 =[tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =[[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =[NSPropertyListSerialization propertyListFromData:tempData
                                                    mutabilityOption:NSPropertyListImmutable
                                                              format:NULL
                                                    errorDescription:NULL];
    return str;
}
-(int) lBytesToInt:(Byte[]) byte
{
    //    int i;
    //    [[NSData data] getBytes:&i length:sizeof(i)];
    int height = 0;
    NSData * testData =[NSData dataWithBytes:byte length:4];
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte[[testData length]-i] >= 0)
        {
            height = height + byte[[testData length]-i];
        } else
        {
            height = height + 256 + byte[[testData length]-i];
        }
        height = height * 256;
    }
    if (byte[0] >= 0)
    {
        height = height + byte[0];
    } else {
        height = height + 256 + byte[0];
    }
    return height;
}
//获取当地时间
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM dd yyyy HH:mm:ss"];
    NSString *dateTime =[NSString stringWithFormat:@"%@ GMT+0800",[formatter stringFromDate:[NSDate date]]];
    NSLog(@"yyyy MM dd HH:mm:ss%@",dateTime);
    
    return dateTime;
}
-(NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
- (void)stop
{
    [timer invalidate];
}

@end
